ALTER PROCEDURE [dbo].[SPForumsGetByCategory]
	@UserGroupId smallint=NULL
AS

SELECT
	F.ForumId
	,F.ForumName
	,F.ForumShortName
	,F.ForumDescription
	,F.UserId
	,F.ForumCreationDate
	,F.ForumTopicCount
	,F.ForumMessageCount
	,C.CategoryId
	,C.CategoryName
	,T.TopicId
	,T.TopicCreationDate
	,T.TopicTitle
	,T.TopicShortName
	,TU.UserId
	,TU.UserName
	
FROM
	ForumsCategories C
	INNER JOIN Forums F ON F.CategoryId = C.CategoryId
	
	LEFT OUTER JOIN	Topics T on T.TopicId = 
		(
			Select top 1 TopicId from Topics 
			where ISNULL(Topics.ReadAccessGroupId,-1) <= ISNULL(@UserGroupId,-1) and F.ForumId = Topics.ForumId 
			Order By TopicId Desc
		)
	LEFT OUTER JOIN	USERS TU on TU.UserId = T.UserId
	
WHERE
	F.Active = 1
	AND
	ISNULL(F.ReadAccessGroupId,-1) <= ISNULL(@UserGroupId,-1)
ORDER BY
	C.CategoryOrder,
	F.ForumOrder
GO